package org.zjt.spring.test.demo.common;

import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.function.Function;

/**
 * Description:  处理异常：
 *
 *                      1、包装 Function :  实例化出一个UncheckedFunction可抛出异常的方法，用来存放check 异常的方噶。
 *                      2、保装 supplier
 *                      3、保装 consumer
 *
 * @author juntao.zhang
 * Date: 2018-05-23 下午12:05
 * @see
 */
@Slf4j
public class ThrowableWrapper {

    public static <T, R> Function<T, R> wrap(UncheckedFunction<T, R>  function) {
        Objects.requireNonNull(function);
        return t -> {
            try {
                return function.apply(t);
            } catch (Throwable ex) {
                throw new RuntimeException(ex);
            }
        };
    }



    public static <T, R> Function<T, R> wrap( UncheckedFunction<T, R>  function, R defaultResult,String  errMsg) {
        Objects.requireNonNull(function);
        return t -> {
            try {
                return function.apply(t);
            } catch (Throwable ex) {
                log.error(errMsg + "{}",ex);
                return defaultResult;
            }
        };
    }



    @FunctionalInterface
    public interface UncheckedFunction<T, R> {

        /**
         * 包装抛出异常的lambda表达式。
         * @param t
         * @return
         * @throws Throwable
         */
        R apply(T t) throws Throwable;
    }


    @FunctionalInterface
    public interface UncheckedSupplier<T> {

        /**
         * 包装可抛出检查异常的 Supplier
         * @return
         * @throws Throwable
         */
        T get() throws Throwable;

    }


    @FunctionalInterface
    public interface UncheckedConsumer<T> {

        /**
         *  包装可抛出检查异常的 Consumer
         * @param t
         * @throws Throwable
         */
        void accept(T t) throws Throwable;
    }
}
